<template>
  <div class="">
    <div class="mainCon">
      <div class="containercontent">
        <div class="selectw100 seachTip" style="line-height: 25px;">
          <div class="inlineblock verticalmiddle infoitem">
            <div class="inlineblock verticalmiddle">
              仪器名称
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-input style="" v-model="demand.name" size="mini" clearable placeholder="仪器名" @keyup.enter.native="doSearch"></el-input>
            </div>
          </div>
          <div class="inlineblock verticalmiddle infoitem">
            <div class="inlineblock verticalmiddle">
              仪器状态
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-select v-model="errorValue" placeholder="请选择" size="mini" clearable @change="doSearch">
                <el-option v-for="item in statusList" :key="item.value" :label="item.name" :value="item.value">
                </el-option>
              </el-select>

            </div>
          </div>
          <div class="inlineblock verticalmiddle infoitem">
            <div class="inlineblock verticalmiddle">
              负责人
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-select v-model="demand.custodian" placeholder="请选择" size="mini" clearable @change="doSearch" filterable>
                <el-option v-for="item in userData" :key="item.account" :label="item.name" :value="item.account" >
                </el-option>
              </el-select>

            </div>
          </div>
          <div class="inlineblock basicRightDistanceA searchIcon">
            <el-button size="mini" @click="doSearch">搜索</el-button>
            <el-button size="mini" @click="emptySearch">清空</el-button>
          </div>
        </div>
        <div class="separaterowTable">
          <div class="tableTittle">
            <div><span class="fontImpact">1</span><span>仪器列表</span></div>
            <form id="fileForm1" style="display:none">
              <input type="file" name="file" id="file1" @change="upload1">
            </form>
            <el-button type="primary"  size="mini" @click="downloadTem" style="float:right;margin-left: 10px;" v-if="userOpernation.upload.display">下载模板</el-button>
            <el-button type="primary"  size="mini" @click="importExcel" style="float:right;" v-if="userOpernation.upload.display">导入</el-button>
            <el-button type="primary" size="mini" @click="exportConfirm" style="float:right;" v-if="userOpernation.export.display">导出确认表</el-button>
            <el-button type="primary" size="mini" @click="exportPlan" style="float:right;" v-if="userOpernation.export.display">导出计划表</el-button>
            <el-button type="primary"  size="mini" @click="downloadEquip" style="float:right;" v-if="userOpernation.export.display">导出台账</el-button>
            <el-button type="primary" size="mini" @click="add" style="float:right" v-if="userOpernation.add.display">添加仪器</el-button>

          </div>
          <el-table :data="tableData" style="width: 100%;height:calc(100% - 86px);" class="tableCon" size="mini" highlight-current-row @current-change="handleCurrentChangeMain" :cell-class-name="cellClassName">
            <el-table-column label="序号"  min-width="50px">
              <template slot-scope="scope">
                {{scope.$index+(readQuery.page - 1) * readQuery.pageCount + 1}}
              </template>
            </el-table-column>
            <el-table-column property="ename"  label="仪器名称"   min-width="150px" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column property="model"  label="规格型号"  min-width="100px" show-overflow-tooltip>
            </el-table-column>
            <el-table-column property="enterCode" label="设备编号" show-overflow-tooltip min-width="100px">
            </el-table-column>
            <el-table-column property="custodianName" label="负责人" show-overflow-tooltip min-width="100px" >
              <template slot-scope="scope">
                {{scope.row.custodianName == undefined || scope.row.custodianName == ''?"---":scope.row.custodianName}}
              </template>
            </el-table-column>
            <el-table-column property="location" label="位置" show-overflow-tooltip min-width="150px" >
              <template slot-scope="scope">
                {{scope.row.location == undefined || scope.row.location == ''?"---":scope.row.location}}
              </template>
            </el-table-column>
            <el-table-column property="maintainStatus   " label="保养状态" min-width="90px">
              <template slot-scope="scope">
								<span :style="{ color: scope.row.maintainStatus == 3?'red':'' }">
									  {{ scope.row.maintainStatus == 3?"异常":"正常"}}
								</span>
              </template>
            </el-table-column>
            <el-table-column property="calibrationStatus" label="检定校准状态" min-width="100px">
              <template slot-scope="scope">
								<span :style="{ color: scope.row.calibrationStatus == 3?'red':'' }">
								    {{ scope.row.calibrationStatus == 3?"异常":"正常"}}
								</span>
              </template>
            </el-table-column>
            <el-table-column property="checkStatus" label="期间核查状态" min-width="100px">
              <template slot-scope="scope">
								<span :style="{ color: scope.row.checkStatus == 3?'red':'' }">
									   {{ scope.row.checkStatus == 3?"异常":"正常"}}
								</span>
              </template>
            </el-table-column>

            <el-table-column property="status" label="状态" min-width="90px" :formatter="formatter">

            </el-table-column>
            <el-table-column label="操作" min-width="200px">
              <template slot-scope="scope">
                <el-button @click="editStatus(scope.row)" type="text" size="mini" v-if="userOpernation.disable.display && scope.row.status == '1'">停用</el-button>
                <el-button @click="editStatus(scope.row)" type="text" size="mini" v-if="userOpernation.enable.display && scope.row.status == '0'">启用</el-button>
                <el-button @click="edit(scope.$index, scope.row)" type="text" size="mini" v-if="scope.row.status != 0 && userOpernation.update.display">编辑</el-button>
                <el-button type="text" size="mini" @click="detail(scope.$index, scope.row)" v-if=" userOpernation.select.display">详情</el-button>
                <el-button type="text" size="mini" @click="del(scope.$index, scope.row)" v-if=" userOpernation.delete.display">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block changepages">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="readQuery.page" :page-sizes="[20, 30, 40]"
              :page-size="readQuery.pageCount" layout="total, sizes, prev, pager, next, jumper" :total="rowNumber">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <div v-if="addShow">
      <add-instrument></add-instrument>
    </div>
    <div v-if="editShow">
      <edit-instrument :editData="editData"></edit-instrument>
    </div>
    <div v-if="detailShow">
      <detail-instrument :detailData="detailData" :showTabIndex="showTabIndex"></detail-instrument>
    </div>

    <confirm-grid :confirmDialogVisible.sync="centerDialogVisible" :queryData.sync="queryData" :confirmData.sync="confirmData"></confirm-grid>

    <plan-grid :planDialogShow.sync="planVisible" :planData.sync="planData" :queryData.sync="queryData"></plan-grid>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  // const instrumentDetail = () => import('./children/instrumentDetail.vue')
  const addInstrument = () => import('./instrumentPage/Add.vue')
  const editInstrument = () => import('./instrumentPage/Edit.vue')
  const detailInstrument = () => import('./instrumentPage/Detail.vue')
  const confirmGrid = () => import('./instrumentPage/confirmGrid.vue') //导出确认表
  const planGrid = () => import('./instrumentPage/planGrid.vue')

  export default {
    components: {
      // instrumentDetail,
      addInstrument,
      editInstrument,
      detailInstrument,
      confirmGrid,
      planGrid
    },
    data() {
      return {
        confirmData: [],
        planData: [],
        modeArr: [{
          name: '检定校准',
          value: 'MA02'
        },
        {
          name: '期间核查',
          value: 'MA03'
        }],
        planVisible: false,
        queryData: {
          maintainType: 'MA02',
          year: new Date().getFullYear()
        },
        centerDialogVisible: false,
        showTabIndex: [],
        addShow: false,
        editShow: false,
        editData: {},
        detailShow: false,
        detailData: {},
        //主仪器列表选中行
        currentRowMain: null,
        eqDetailShow: false,
        //表示仪器详细信息显示权限
        eqDetailShowType: '',
        //仪器详情中，是主仪器还是辅助仪器
        eqType: '',
        //仪器详情中，是新增仪器还是编辑仪器
        eqEditOrNew: '',
        tableData: [],
        pageinfo: {
          totalPage: null
        },
        readQuery:{
          page: 1,
          pageCount: 20,
        },
        rowNumber:0,
        demand: {
          name: '',
          custodian:'',
        },
        statusList:[
          {name:'仪器保养异常',value:"maintainStatus"},
          {name:'检定校准异常',value:"calibrationStatus"},
          {name:'期间核查异常',value:"checkStatus"},
        ],
        errorValue:"",
        userData:[],

      }
    },
    props: ["userOpernation"],
    computed: {
      ...mapState(['enableStatus', 'tableHeightB', 'tableHeight', 'mainEquipType', 'frontEquipType', 'mainEquipTableData', 'frontEquipTableData', 'eqTypeArr'])
    },
    mounted() {
      this.errorValue = this.$store.state.unnormalValue;
      this.init()
      this.getUser();
    },
    beforeDestroy(){
      this.$store.state.unnormalValue = ""
    },
    watch:{
      readQuery: {
        handler(val, oldVal) {
          this.init()
        },
        deep: true
      },
    },
    methods: {
			cellClassName({row, column, rowIndex, columnIndex}){
				// console.log({row, column, rowIndex, columnIndex})
				 if (column.label =='状态'&&row.status==0) {
          return 'danger-cell';
        }
        return '';

			},
      //处理状态
      formatter(row, column, cellValue, index) {
        return this.util.changeStatus({ cellValue: cellValue, list: this.enableStatus })
      },
      calibrationExport() {
        let url = 'resource/calibrationExport.htm'
         let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
        window.open(process.env.baseUrl + url  + '?token=' + token);
        this.centerDialogVisible = false

      },
      exportConfirm() {
        let params = this.queryData
        this.$http({
          apiUrl: 'resource/getCalibrationList.htm',
          method: 'post',
          params: params,
          isJson: false
        }).then(res => {
          if (res.code == 0) {
            this.confirmData = res.data
            this.centerDialogVisible = true
          }
        })
        //						window.open('resource/calibrationExport.htm')

      },
      planExport() {
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
        let url = 'resource/planExport.htm?maintainType=' + this.queryData.maintainType + '&year=' + this.queryData.year + "&token=" + token
        window.open(process.env.baseUrl + url);
        this.planVisible = false
      },
      exportPlan() {
        let params = this.queryData
        this.$http({
          apiUrl: 'resource/getPlanList.htm',
          method: 'post',
          params: params,
          isJson: false
        }).then(res => {
          if (res.code == 0) {
            this.planData = res.data
            this.planVisible = true
          }
        })
        //						window.open('resource/calibrationExport.htm')

      },
      editStatus(row) {
        var msg = row.status == 0 ? "启用" : "停用";
        this.$confirm("是否" + msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            this.$http({
              apiUrl: 'resource/updateEquipmentStatus.htm',
              method: 'post',
              params: { id: row.id, status: row.status == 0 ? 1 : 0 },
              isJson: false
            }).then(res => {
              if (res.code == 0) {
                this.$message({
                  showClose: true,
                  message: '修改成功！',
                  type: 'success'
                })
                this.init()
              }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消' + msg
          });
        });

      },
      emptySearch(){
        this.demand.name = "";
        this.demand.custodian = ''
        this.errorValue = "";
        this.init();
      },
      doSearch(){
        this.readQuery.page = 1;
        this.init();
      },
      getUser(){
        this.$http({
          method: 'post',
          apiUrl: '/resource/readEmployeeByLab.htm',
          params: { name: '' },
          isJson: true,
        }).then(res => {
          if (res.code === 0) {
            this.userData = res.data;
          }

        })
      },
      init() {
        this.demand.page = this.readQuery.page;
        this.demand.pageCount = this.readQuery.pageCount;
        if(this.errorValue != ""){
          this.$set(this.demand,this.errorValue,3)
        }
        if(this.errorValue == 'maintainStatus'){
          delete this.demand.checkStatus;
          delete this.demand.calibrationStatus;
        }else if(this.errorValue == 'checkStatus'){
          delete this.demand.maintainStatus;
          delete this.demand.calibrationStatus;
        }else if(this.errorValue == 'calibrationStatus'){
          delete this.demand.checkStatus;
          delete this.demand.maintainStatus;
        }else{
          delete this.demand.checkStatus;
          delete this.demand.maintainStatus;
          delete this.demand.calibrationStatus;
        }
        this.$http({
          apiUrl: 'resource/readEquipmentList.htm',
          method: 'post',
          params: this.demand,
        }).then(res => {
          if (res.code == 0) {
            this.tableData = res.data

            this.pageinfo = res.pageinfo
            if (!res.pageinfo) {
              this.rowNumber = 0;
            } else if (res.pageinfo && !res.pageinfo.rowNumber) {
              this.rowNumber = 0;
            } else {
              this.rowNumber = res.pageinfo.rowNumber;
            }
          }
        })

      },
      importExcel() { // 模拟file的点击事件
        document.getElementById("file1").click()
      },
      // 导入文件
      upload1(event) {
        var files = document.getElementById('file1').files[0];
        var formData = new FormData();
        formData.append('file', files)
        this.$axios({
          method: 'post',
          url: '/resource/getEquipByExcel.htm',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data',
             'token':sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined,
          }
        }).then(res => {
          event.target.value= "";
          if (res.data.code == 0) {
            this.$notify({
              title: '消息',
              message: res.data.description,
              type: 'success'
            })
           this.init()
          } else {
            this.$notify({
              title: '消息',
              type: 'warning',
              message: res.data.description,
            })
          }

        })
      },
      downloadEquip(){
          var url = "/resource/exportEquipExcel.htm";

          let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
          if(this.errorValue == 'maintainStatus'){
           window.open(process.env.baseUrl + url + '?name=' + this.demand.name + '&custodian=' + this.demand.custodian + "&maintainStatus=" + 3 + "&token=" + token)
          }else if(this.errorValue == 'checkStatus'){
            window.open(process.env.baseUrl + url + '?name=' + this.demand.name + '&custodian=' + this.demand.custodian + "&checkStatus=" + 3 + "&token=" + token)
          }else if(this.errorValue == 'calibrationStatus'){
            window.open(process.env.baseUrl + url + '?name=' + this.demand.name + '&custodian=' + this.demand.custodian + "&calibrationStatus=" + 3 + "&token=" + token)
          }else{
            window.open(process.env.baseUrl + url + '?name=' + this.demand.name + '&custodian=' + this.demand.custodian + "&token=" + token)
          }

      },
      //
      downloadTem(){
        var url = "/resource/getEquipMould.htm";
        var template = "resource";
        var module = "equipment";
        var name = "equipmentData"
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
        window.open(process.env.baseUrl + url + '?template=' + template + '&module=' + module + "&name=" + name + "&token=" + token)
      },

      handleCurrentChangeMain(val) {
        this.currentRowMain = val
      },
      handleCurrentChange(val) {
        this.readQuery.page = val

      },
      handleSizeChange(val) {
        this.readQuery.pageCount = val

      },
      add() {
        this.addShow = true
      },
      edit(index, row) {

        this.editData = row
        this.editShow = true
      },
      detail(index, row) {
        this.detailShow = true
        this.showTabIndex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
        this.detailData = row

      },
      del(index, row) {
        this.$confirm('是否删除' + row.name + '的仪器信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            apiUrl: 'resource/deleteEquipment.htm',
            method: 'get',
            params: { id: row.id },
          }).then(res => {
            if (res.code === 0) {
              this.init()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
        }).catch(() => { })
      }
    }
  }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
	 .el-table .danger-cell {
    color: red;
  }
</style>
<style scoped>
  .separaterow {
    margin-top: 10px;
  }
  .seachTip .infoitem{
    width: calc(100%/4);
  }
  .informationItem {
    width: calc(100% - 70px);
    float: right;
  }
</style>
